package com.imooc.mq.activemq;


import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;

public class ActivemqMain {
    private static final  String url="tcp://192.168.207.130:61616";
    private static final  String queryName="queue-test";

    public static void main(String[] args) throws JMSException {
        //创建ConnectionFactory 链接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(url);
        //connection 链接
        Connection connection=connectionFactory.createConnection();
        //启动
        connection.start();;
        //创建会话，参数说明：是否在事物中处理，应答模式自动应答
        Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

        //创建目标
        Destination destination=session.createQueue(queryName);

        //发送消息
//        sendMeassage(connection,session,destination);
        //接收消息
        getMeassage(session,destination);


    }

    public static void sendMeassage(Connection connection,Session session,Destination destination) throws JMSException {
        //创建生成者
        MessageProducer producer=session.createProducer(destination);
        //发送消息
        for (int i = 0; i <100 ; i++) {
            TextMessage textMessage=session.createTextMessage("test"+i);
            producer.send(textMessage);
            System.out.println("发送消息"+textMessage.getText());
        }
        //关闭链接
        connection.close();
    }

    public static void getMeassage(Session session,Destination destination) throws JMSException {
        MessageConsumer consumer=session.createConsumer(destination);
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage=(TextMessage)message;
                try {
                    System.out.println("收到消息"+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
